package com.sl.au.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.sl.au.config.AppWebSocketTask;

import com.sl.au.entity.SocketMessage;
import com.sl.au.entity.Account;
import com.sl.au.entity.ArchiveReportInfo;
import com.sl.au.entity.BussinessContent;
import com.sl.au.entity.Comment;
import com.sl.au.entity.Division;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventType;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Module;
import com.sl.au.entity.News;
import com.sl.au.entity.Option;
import com.sl.au.entity.Role;
import com.sl.au.entity.User;
import com.sl.au.entity.UserTrajectory;
import com.sl.au.entity.MessageVerification;
import com.sl.au.repository.MessageVerificationRepository;
import com.sl.au.service.AccountService;
import com.sl.au.service.ArchiveReportInfoService;
import com.sl.au.service.BussinessContentService;
import com.sl.au.service.CommentService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.ModuleService;
import com.sl.au.service.NewsService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.RoleService;
import com.sl.au.service.UserService;
import com.sl.au.service.UserTrajectoryService;
import com.sl.utils.ExdeUtil;

import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "/ui/userTrajectory")
public class UserTrajectoryController extends BaseController {

	@Autowired
	UserTrajectoryService userTrajectoryService;
	@Autowired
	AccountService accountService;
	
	@RequestMapping(value = "/setUserTrajectory", method = RequestMethod.POST)
	public Map<String, Object> setUserTrajectory(HttpServletRequest request) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
	    String jsonStr = this.getJson(request);

	    if (jsonStr != null ) {
	    		JSONObject json = JSONObject.fromObject(jsonStr);
	    		double longitude = ExdeUtil.str2double((String) json.get("longitude"));
	    		double latitude = ExdeUtil.str2double((String) json.get("latitude"));
	    		String userName = json.getString("userName");
	    		userName =  URLDecoder.decode(URLDecoder.decode(userName,"UTF-8"),"UTF-8");
	    		String userPwd = json.getString("userPwd");
	    		Account account = accountService.getRepository().findByAccountNameOrPhoneNumberAndPassword(userName, userPwd);
	    		if(account != null) {
		    		UserTrajectory userTrajectory = new UserTrajectory();
		    		userTrajectory.setUser(account.getUser());
		    		userTrajectory.setLongitude(longitude);
		    		userTrajectory.setLatitude(latitude);
		    		userTrajectoryService.getRepository().save(userTrajectory);
		    		map.put("user", userTrajectory);
		    		this.pushPersonLocation(map,account.getUser().getId());
	    		}
	    }
		
		return map;
	}
	@RequestMapping(value = "/setUserTrajectoryIOS", method = RequestMethod.POST)
	public Map<String, Object> setUserTrajectoryIOS(HttpServletRequest request) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();	    		
	    		double longitude = ExdeUtil.str2double((String)request.getParameter("longitude"));
	    		double latitude = ExdeUtil.str2double((String)request.getParameter("latitude"));
	    		String userName = request.getParameter("userName");
	    		String userPwd = request.getParameter("userPwd");
	    		Account account = accountService.getRepository().findByAccountNameOrPhoneNumberAndPassword(userName, userPwd);
	    		if(account != null) {
		    		UserTrajectory userTrajectory = new UserTrajectory();
		    		userTrajectory.setUser(account.getUser());
		    		userTrajectory.setLongitude(longitude);
		    		userTrajectory.setLatitude(latitude);
		    		userTrajectoryService.getRepository().save(userTrajectory);
		    		map.put("user", userTrajectory);
		    		this.pushPersonLocation(map,account.getUser().getId());
	    		}
		return map;
	}
	private void pushPersonLocation(Map<String, Object> map,String userid){
		try {			
				if (AppWebSocketTask.webSocketSet != null) {
					SocketMessage message = new SocketMessage();
					message.setOnlinePerson(null);
					for (AppWebSocketTask item : AppWebSocketTask.webSocketSet) {
						try {
							if (item.getLocation().equals("followPersonLocation"+userid)) {
									message.setDealEventOverTime(null);
									message.setReceiveEventOverTime(null);
									message.setRejectConfirm(null);
									message.setWaitingPublic(null);
									message.setWaitingAccept(null);
									message.setFollowMap(map);
									item.sendMessage(JSONObject.fromObject(message).toString());
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}			
		} catch (Exception ex) {

		}
	}
	
	private String getJson(HttpServletRequest request) throws IOException {
		//使用字符流读取客户端发过来的数据  
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));  
        String line = null;  
        StringBuffer s = new StringBuffer();  
        while ((line = br.readLine()) != null) {  
            s.append(line);  
        }  
        br.close();
        return s != null ? s.toString() : null;
	}

	@RequestMapping(value = "/getOnlineUser", method = RequestMethod.GET)
	public Map<String, Object> getOnlineUser(HttpServletRequest request) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> online = userTrajectoryService.getOnlineUser(this.getOnline());
		map.put("online", online);
		return map;
	}
}
